package ua.kharkov.khpi.tarasenko.bach.web.command.common;

import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.item.ItemListBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.item.ItemDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to show list with items
 * 
 * @author oleksandr
 * 
 */
public class ShowItemsListCommand extends Command {
	private static final Logger log = Logger
			.getLogger(ShowItemsListCommand.class);
	
	private static final String ATTRIBUTE_ITEMS_LIST = "itemsList";
	private static final int DEFAULT_CATEGORY_ID = 0;

	/**
	 * Comparator to compare ItemListBeans by price. The resulting list will be
	 * starting from the highest to the lowest.
	 * 
	 * @author oleksandr
	 * 
	 */
	private static class CompareByPrice implements Comparator<ItemListBean>,
			Serializable {
		private static final long serialVersionUID = 7827795623817114085L;

		@Override
		public int compare(ItemListBean o1, ItemListBean o2) {
			if (o1.getPrice() > o2.getPrice()) {
				return -1;
			} else if (o1.getPrice() < o2.getPrice()) {
				return 1;
			} else {
				return 0;
			}
		}
	}

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		Connection conn = null;
		String forward = Constant.PAGE_ITEMS_LIST;

		String categoryIdString = request
				.getParameter(Constant.ATTRIBUTE_CATEGORY_ID);
		if (log.isTraceEnabled()) {
			log.trace("Got parameter from request "
					+ Constant.ATTRIBUTE_CATEGORY_ID + "=" + categoryIdString);
		}

		// Check id of category to show.
		int categoryId = 0;
		if ((categoryIdString == null) || (categoryIdString.isEmpty())) {
			categoryId = DEFAULT_CATEGORY_ID;
		} else {
			categoryId = Integer.valueOf(categoryIdString);
		}

		try {
			conn = ConnectionManager.getConnection();
			List<ItemDTO> items = DAOFactory
					.getDAOFactory(DAOFactory.DAO_TYPE.MYSQL).getItemDAO(conn)
					.findItemsByCategory(categoryId);

			// Extract all info we need from DTO and put it into ItemListBean
			List<ItemListBean> beans = new ArrayList<ItemListBean>();
			for (ItemDTO itemDTO : items) {
				beans.add(createItemListBean(itemDTO));
			}

			// Sort items by price
			Collections.sort(beans, new CompareByPrice());

			// Put category id into request to know what category is displaying
			// now
			request.setAttribute(Constant.ATTRIBUTE_CATEGORY_ID, categoryId);
			if (log.isTraceEnabled()) {
				log.trace("Set request attribute "
						+ Constant.ATTRIBUTE_CATEGORY_ID + "=" + categoryId);
			}

			// Put all items into request
			request.setAttribute(ATTRIBUTE_ITEMS_LIST, beans);
			if (log.isTraceEnabled()) {
				log.trace("Set request attribute " + ATTRIBUTE_ITEMS_LIST
						+ ":\n" + beans);
			}
		} catch (EShopException e) {
			DBUtils.close(conn);
			throw e;
		} finally {
			if (conn != null) {
				DBUtils.close(conn);
			}
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}

	/**
	 * Creates ItemListBean from ItemDTO
	 * 
	 * @param itemDTO
	 * @return itemListBean
	 */
	private ItemListBean createItemListBean(ItemDTO itemDTO) {
		ItemListBean bean = new ItemListBean();
		bean.setId(itemDTO.getId());
		bean.setName(itemDTO.getName());
		bean.setPrice(itemDTO.getPrice());
		bean.setCategory(itemDTO.getCategory());

		int quantity = itemDTO.getQuantity();

		if (quantity >= 1) {
			bean.setIsAvailable(true);
		} else {
			bean.setIsAvailable(false);
		}
		return bean;
	}
}
